package org.texteasy;

import java.util.HashSet;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.DatabaseUtils.InsertHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class TextEasyDBAdapter {

	public static final String KEY_ROWID = "_id";
	public static final String KEY_SELECTED_ID = "selectedId";
	
	private static final String DATABASE_NAME = "easy_text";
    private static final String DATABASE_TABLE = "selected_ids";
    private static final int DATABASE_VERSION = 3;
	
	private DatabaseHelper dbHelper;
	
    private final Context context;
    
    private static class DatabaseHelper extends SQLiteOpenHelper{
    	
    	DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }
    	
    	@Override
    	public void onCreate(SQLiteDatabase db) {
    		db.execSQL("create table selected_ids (_id integer primary key autoincrement," +
				"selectedId varchar not null);");
    	}
    	
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		db.execSQL("DROP TABLE IF EXISTS selected_ids");
            onCreate(db);
    	}
    	
    }
    
    public TextEasyDBAdapter(Context context){
    	
    	if(context == null){
    		throw new IllegalArgumentException("This method does not accept " +
				"null parameters");
    	}
    	this.context = context;
    }
    
    /**
     * Open the selected_ids database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     * 
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public TextEasyDBAdapter open() throws SQLException {
        dbHelper = new DatabaseHelper(this.context);
        return this;
    }
    
    public boolean isOpen(){
    	SQLiteDatabase database = dbHelper.getWritableDatabase();
    	return database.isOpen();
    }
    
    public void close() {
    	SQLiteDatabase database = dbHelper.getWritableDatabase();
        database.close();
        dbHelper.close();
    }
    
    public void persistSelectedIds(HashSet<String> selectedIds){
    	
    	SQLiteDatabase database = dbHelper.getWritableDatabase();
    	InsertHelper insertHelper = new InsertHelper(database, DATABASE_TABLE);
    	database.beginTransaction();
    	try{
	    	ContentValues initialValues = null;
	    	for(String selectedId: selectedIds){
	    		initialValues = new ContentValues();
	    		initialValues.put(KEY_SELECTED_ID, selectedId);
	    		insertHelper.insert(initialValues);
	    	}
	    	database.setTransactionSuccessful();
    	}finally{
    		database.endTransaction();
    	}
    	
    	database.close();
    }
    
    public HashSet<String> getSelectedIdsAndClear(){
    	
    	SQLiteDatabase database = dbHelper.getWritableDatabase();
    	
    	Cursor cursor = database.query(DATABASE_TABLE, 
			new String[]{KEY_SELECTED_ID}, null,null,
			null,null,null); 
    	
    	HashSet<String> selectedIds = new HashSet<String>();
    	
    	while(cursor.moveToNext()){
    		selectedIds.add(cursor.getString(cursor.
				getColumnIndexOrThrow(KEY_SELECTED_ID)));
    	}
    	database.delete(DATABASE_TABLE, null, null);
    	cursor.close();
    	database.close();
    	return selectedIds;
    }
}
